<?php
namespace doujunyu\utility\ali;

use AlipayConfig;
use AlipayTradeAppPayRequest;
use AlipayTradeCreateRequest;
use AlipayTradePagePayRequest;
use AopClient;

// require '../extend/Pay/AliPay/sdk/aop/AopClient.php';

require_once  dirname(__FILE__).'/alipaysdk/v2/aop/AopClient.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/AopCertClient.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/AopCertification.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/AlipayConfig.php';
// require_once '../extend/utility/ali/alipaysdk/aop/AlipayConfig.php';
// require_once dirname(__FILE__).'/alipaysdk/aop/AlipayConfig.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/request/AlipayTradePagePayRequest.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/request/AlipayTradeAppPayRequest.php';
require_once  dirname(__FILE__).'/alipaysdk/v2/aop/request/AlipayTradeCreateRequest.php';


class AliPay{
    private $app_id = "appid";
    private $merchant_private_key = "秘钥";
    private $notify_url = "http://外网可访问网关地址/alipay.trade.page.pay-PHP-UTF-8/notify_url.php";
    private $return_url = "http://外网可访问网关地址/alipay.trade.page.pay-PHP-UTF-8/return_url.php";
    private $charset = "UTF-8";
    private $sign_type = "RSA2";
    private $gatewayUrl = "https://openapi.alipay.com/gateway.do";
    // private $gatewayUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";//沙箱模式
    private $alipay_public_key = "支付宝公钥";

    private $alipayConfig = null;

    public function __construct($app_id,$merchant_private_key,$alipay_public_key,$notify_url = '',$return_url = '') {
        $this->app_id = $app_id;//应用ID,您的APPID。
        $this->merchant_private_key = $merchant_private_key;//商户私钥
        $this->notify_url = $notify_url;//异步通知地址
        $this->return_url = $return_url;//同步跳转
        $this->alipay_public_key = $alipay_public_key;//支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。

        $privateKey  = $this->merchant_private_key;
        $alipayPublicKey = $this->alipay_public_key;
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setServerUrl($this->gatewayUrl);
        $alipayConfig->setAppId($this->app_id);
        $alipayConfig->setPrivateKey($privateKey);
        $alipayConfig->setFormat('json');
        $alipayConfig->setAlipayPublicKey($alipayPublicKey);
        $alipayConfig->setCharset('UTF-8');
        $alipayConfig->setSignType('RSA2');
        $this->alipayConfig = $alipayConfig;

    }

    /** 下单
     *  https://opendocs.alipay.com/open/59da99d0_alipay.trade.page.pay?scene=22&pathHash=e26b497f
     * 实例
     *  $alipay = new AliPay(
     *      config('system.ali_app_id'),
     *      config('system.ali_private_key'),
     *      config('system.ali_alipay_public_key'),
     *      "https://".$_SERVER['HTTP_HOST'].'/api/notify/alipay',
     *      "https://".$_SERVER['HTTP_HOST'].'/api/index/index'
     *  );
     *  $url = $alipay->add([
     *      'out_trade_no' => 'demod'.time(),
     *      'total_amount' => '0.01',
     *      'subject' => '测试订单',
     *      // 'merchant_order_no' => 'ttt'.random_int(1000,9999)
     *  ]);
     *  $this->success('请求成功',$url);
     * 
     */
    public function pc_pay($model_param = []){
        // 初始化SDK
        $alipayClient = new AopClient($this->alipayConfig);
        // 构造请求参数以调用接口
        $request = new AlipayTradePagePayRequest();
        $model = array();

        // 设置商户订单号
        $model['out_trade_no'] = $model_param['out_trade_no'] ?? '';

        // 设置订单总金额
        $model['total_amount'] = $model_param['total_amount'] ?? '';

        // 设置订单标题
        $model['subject'] = $model_param['subject'] ?? '';

        // 设置产品码
        $model['product_code'] = "FAST_INSTANT_TRADE_PAY";

        // 设置PC扫码支付的方式
        if(isset($model_param['qr_pay_mode'])){
            $model['qr_pay_mode'] = $model_param['qr_pay_mode'];
        }
        

        // 设置商户自定义二维码宽度
        if(isset($model_param['qrcode_width'])){
            $model['qrcode_width'] = $model_param['qrcode_width'];
        }

        // 设置订单包含的商品列表信息
        
        // 设置订单包含的商品列表信息
        if(isset($model_param['goods_detail'])){
            $goodsDetail = array();
            foreach($model_param['goods_detail'] as $val){
                $goodsDetail0 = array();
                $goodsDetail0['goods_name'] = $val['goods_name'] ?? "ipad" ;
                $goodsDetail0['alipay_goods_id'] = $val['alipay_goods_id'] ?? "20010001";
                $goodsDetail0['quantity'] = $val['quantity'] ?? 1;
                $goodsDetail0['price'] = $val['price'] ?? "2000";
                $goodsDetail0['goods_id'] = $val['goods_id'] ?? "apple-01";
                $goodsDetail0['goods_category'] = $val['goods_category'] ?? "34543238";
                $goodsDetail0['categories_tree'] = $val['categories_tree'] ?? "124868003|126232002|126252004";
                $goodsDetail0['show_url'] = $val['show_url'] ?? "http://www.alipay.com/xxx.jpg";
                $goodsDetail[] = $goodsDetail0;
                
            }
            $model['goods_detail'] = $goodsDetail;
            
        }

        // 设置订单绝对超时时间
        $model['time_expire'] = $model_param['time_expire'] ?? date('Y-m-d H:i:s',time() + 600);

        // 设置二级商户信息
        if(isset($model_param['sub_merchant'])){
            $subMerchant = array();
            $subMerchant['merchant_id'] = $model_param['sub_merchant']['merchant_id'] ?? "2088000603999128";
            $subMerchant['merchant_type'] = $model_param['sub_merchant']['merchant_type'] ?? "alipay";
            $model['sub_merchant'] = $subMerchant;
        
        }

        // 设置业务扩展参数
        // 设置业务扩展参数
        if(isset($model_param['extend_params'])){
            $extendParams = array();
            // $extendParams['sys_service_provider_id'] = "2088511833207846";
            // $extendParams['hb_fq_seller_percent'] = "100";
            // $extendParams['hb_fq_num'] = "3";
            // $extendParams['industry_reflux_info'] = "{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}";
            // $extendParams['royalty_freeze'] = "true";
            // $extendParams['card_type'] = "S0JP0000";
            $model['extend_params'] = $extendParams;
        }

        // 设置商户传入业务信息
        if(isset($model_param['business_params'])){
            $model['business_params'] = $model_param['business_params'] ?? "{\"mc_create_trade_ip\":\"127.0.0.1\"}";
        }

        // 设置优惠参数 "{\"storeIdType\":\"1\"}"
        if(isset($model_param['promo_params'])){
            $model['promo_params'] = $model_param['promo_params'];
        }

        // 设置请求后页面的集成方式
        if(isset($model_param['integration_type'])){
            $model['integration_type'] = "PCWEB";
        }
        

        // 设置请求来源地址
        if(isset($model_param['request_from_url'])){
            $model['request_from_url'] = "https://";
        }
        

        // 设置商户门店编号 "NJ_001"
        if(isset($model_param['store_id'])){
            $model['store_id'] = "";
        }
        

        // // 设置商户的原始订单号
        if(isset($model_param['merchant_order_no'])){
            $model['merchant_order_no'] = $model_param['merchant_order_no'];
        }

        // 设置外部指定买家
        // $extUserInfo = array();
        // $extUserInfo['cert_type'] = "IDENTITY_CARD";
        // $extUserInfo['cert_no'] = "362334768769238881";
        // $extUserInfo['name'] = "李明";
        // $extUserInfo['mobile'] = "16587658765";
        // $extUserInfo['min_age'] = "18";
        // $extUserInfo['need_check_info'] = "F";
        // $extUserInfo['identity_hash'] = "27bfcd1dee4f22c8fe8a2374af9b660419d1361b1c207e9b41a754a113f38fcc";
        // $model['ext_user_info'] = $extUserInfo;

        // 设置开票信息
        // $invoiceInfo = array();
        // $keyInfo = array();
        // $keyInfo['tax_num'] = "1464888883494";
        // $keyInfo['is_support_invoice'] = true;
        // $keyInfo['invoice_merchant_name'] = "ABC|003";
        // $invoiceInfo['key_info'] = $keyInfo;
        // $invoiceInfo['details'] = "[{\"code\":\"100294400\",\"name\":\"服饰\",\"num\":\"2\",\"sumPrice\":\"200.00\",\"taxRate\":\"6%\"}]";
        // $model['invoice_info'] = $invoiceInfo;
        //https://opendocs.alipay.com/support/01rfuz
        $request->setNotifyUrl($this->notify_url);
        //https://opendocs.alipay.com/support/01raw6?pathHash=2c37d5b1
        $request->setReturnUrl($this->return_url);
        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
        // $pageRedirectionData = $alipayClient->pageExecute($request, "POST", "");//<-- 请填写应用授权令牌 -->
        // 如果需要返回GET请求，请使用
        $pageRedirectionData = $alipayClient->pageExecute($request, "GET");

        return $pageRedirectionData;
    }
    /** 下单
     *  https://opendocs.alipay.com/open/cd12c885_alipay.trade.app.pay?scene=20&pathHash=ab686e33
     * 实例
     *  $alipay = new AliPay(
     *      config('system.ali_app_id'),
     *      config('system.ali_private_key'),
     *      config('system.ali_alipay_public_key'),
     *      "https://".$_SERVER['HTTP_HOST'].'/api/notify/alipay',
     *      "https://".$_SERVER['HTTP_HOST'].'/api/index/index'
     *  );
     *  $url = $alipay->add([
     *      'out_trade_no' => 'demod'.time(),
     *      'total_amount' => '0.01',
     *      'subject' => '测试订单',
     *      // 'merchant_order_no' => 'ttt'.random_int(1000,9999)
     *  ]);
     *  $this->success('请求成功',$url);
     * 
     */
    public function app_pay($model_param = []){
        // 初始化SDK
        $alipayClient = new AopClient($this->alipayConfig);
        // 构造请求参数以调用接口AlipayTradeAppPayRequest
        $request = new AlipayTradeAppPayRequest();
        $model = array();

        // 设置商户订单号
        $model['out_trade_no'] = $model_param['out_trade_no'] ?? '';

        // 设置订单总金额
        $model['total_amount'] = $model_param['total_amount'] ?? '';

        // 设置订单标题
        $model['subject'] = $model_param['subject'] ?? '';

        // 设置产品码
        $model['product_code'] = "FAST_INSTANT_TRADE_PAY";
        // 设置订单包含的商品列表信息
        
        // 设置订单包含的商品列表信息
        if(isset($model_param['goods_detail'])){
            $goodsDetail = array();
            foreach($model_param['goods_detail'] as $val){
                $goodsDetail0 = array();
                $goodsDetail0['goods_name'] = $val['goods_name'] ?? "ipad" ;
                $goodsDetail0['alipay_goods_id'] = $val['alipay_goods_id'] ?? "20010001";
                $goodsDetail0['quantity'] = $val['quantity'] ?? 1;
                $goodsDetail0['price'] = $val['price'] ?? "2000";
                $goodsDetail0['goods_id'] = $val['goods_id'] ?? "apple-01";
                $goodsDetail0['goods_category'] = $val['goods_category'] ?? "34543238";
                $goodsDetail0['categories_tree'] = $val['categories_tree'] ?? "124868003|126232002|126252004";
                $goodsDetail0['show_url'] = $val['show_url'] ?? "http://www.alipay.com/xxx.jpg";
                $goodsDetail[] = $goodsDetail0;
                
            }
            $model['goods_detail'] = $goodsDetail;
            
        }

        // 设置订单绝对超时时间
        $model['time_expire'] = $model_param['time_expire'] ?? date('Y-m-d H:i:s',time() + 600);

        // 设置二级商户信息
        if(isset($model_param['sub_merchant'])){
            $subMerchant = array();
            $subMerchant['merchant_id'] = $model_param['sub_merchant']['merchant_id'] ?? "2088000603999128";
            $subMerchant['merchant_type'] = $model_param['sub_merchant']['merchant_type'] ?? "alipay";
            $model['sub_merchant'] = $subMerchant;
        
        }

        // 设置业务扩展参数
        // 设置业务扩展参数
        if(isset($model_param['extend_params'])){
            $extendParams = array();
            // $extendParams['sys_service_provider_id'] = "2088511833207846";
            // $extendParams['hb_fq_seller_percent'] = "100";
            // $extendParams['hb_fq_num'] = "3";
            // $extendParams['industry_reflux_info'] = "{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}";
            // $extendParams['royalty_freeze'] = "true";
            // $extendParams['card_type'] = "S0JP0000";
            $model['extend_params'] = $extendParams;
        }

        // 设置商户传入业务信息
        if(isset($model_param['business_params'])){
            $model['business_params'] = $model_param['business_params'] ?? "{\"mc_create_trade_ip\":\"127.0.0.1\"}";
        }

        // // 设置商户的原始订单号
        if(isset($model_param['merchant_order_no'])){
            $model['merchant_order_no'] = $model_param['merchant_order_no'];
        }

        // 设置外部指定买家
        // $extUserInfo = array();
        // $extUserInfo['cert_type'] = "IDENTITY_CARD";
        // $extUserInfo['cert_no'] = "362334768769238881";
        // $extUserInfo['name'] = "李明";
        // $extUserInfo['mobile'] = "16587658765";
        // $extUserInfo['min_age'] = "18";
        // $extUserInfo['need_check_info'] = "F";
        // $extUserInfo['identity_hash'] = "27bfcd1dee4f22c8fe8a2374af9b660419d1361b1c207e9b41a754a113f38fcc";
        // $model['ext_user_info'] = $extUserInfo;

        // 设置开票信息
        // $invoiceInfo = array();
        // $keyInfo = array();
        // $keyInfo['tax_num'] = "1464888883494";
        // $keyInfo['is_support_invoice'] = true;
        // $keyInfo['invoice_merchant_name'] = "ABC|003";
        // $invoiceInfo['key_info'] = $keyInfo;
        // $invoiceInfo['details'] = "[{\"code\":\"100294400\",\"name\":\"服饰\",\"num\":\"2\",\"sumPrice\":\"200.00\",\"taxRate\":\"6%\"}]";
        // $model['invoice_info'] = $invoiceInfo;
        //https://opendocs.alipay.com/support/01rfuz
        // $request->setNotifyUrl($this->notify_url);
        //https://opendocs.alipay.com/support/01raw6?pathHash=2c37d5b1
        $request->setReturnUrl($this->return_url);
        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
        // $pageRedirectionData = $alipayClient->pageExecute($request, "POST", "");//<-- 请填写应用授权令牌 -->
        // 如果需要返回GET请求，请使用
        $pageRedirectionData = $alipayClient->sdkExecute($request, "GET");

        return ['',$pageRedirectionData];



    }

    /** 下单
     *  https://opendocs.alipay.com/mini/6039ed0c_alipay.trade.create?pathHash=779dc517&scene=de4d6a1e0c6e423b9eefa7c3a6dcb7a5
     * 实例
     *  $alipay = new AliPay(
     *      config('system.ali_app_id'),
     *      config('system.ali_private_key'),
     *      config('system.ali_alipay_public_key'),
     *      "https://".$_SERVER['HTTP_HOST'].'/api/notify/alipay',
     *      "https://".$_SERVER['HTTP_HOST'].'/api/index/index'
     *  );
     *  $url = $alipay->add([
     *      'out_trade_no' => 'demod'.time(),
     *      'total_amount' => '0.01',
     *      'subject' => '测试订单',
     *       'buyer_open_id' => '测试订单',//支付宝用户唯一标识
     *      // 'merchant_order_no' => 'ttt'.random_int(1000,9999)
     *  ]);
     *  $this->success('请求成功',$url);
     * 
     */
    public function jsapi_pay($model_param = []){
        // 初始化SDK
        $alipayClient = new AopClient($this->alipayConfig);
        // 构造请求参数以调用接口AlipayTradeAppPayRequest
        $request = new AlipayTradeCreateRequest();
        $model = array();

        // 设置商户订单号
        $model['out_trade_no'] = $model_param['out_trade_no'] ?? '';

        // 设置产品码
        $model['product_code'] = "JSAPI_PAY";

        // 设置小程序支付中
        $model['op_app_id'] = $this->app_id;

        // 设置订单总金额
        $model['total_amount'] = $model_param['total_amount'] ?? '';

        // 设置业务扩展参数
        // $extendParams = array();
        // $extendParams['trade_component_order_id'] = "2023060801502300000008810000005657";
        // $model['extend_params'] = $extendParams;

        // 设金置可打折额
        // $model['discountable_amount'] = "80.00";

        // 设置订单标题
        $model['subject'] = $model_param['subject'] ?? '';

        // 设置订单附加信息
        $model['body'] = $model_param['body'] ?? '';

        // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
        // $model['buyer_id'] = "2088102146225135";

        // 设置买家支付宝用户唯一标识
        $model['buyer_open_id'] = $model_param['buyer_open_id'] ?? '';

        // 设置商户门店编号
        // $model['store_id'] = "NJ_001";
        $request->setNotifyUrl($this->notify_url);
        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
        $responseResult = $alipayClient->execute($request, null, "", null);
        $responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
        $response = $responseResult->$responseApiName;
        if(!empty($response->code)&&$response->code==10000){
            return ['',$response];
            // echo("调用成功");
        }
        else{
            return [$response->code.'|'.$response->sub_msg,[]];
        }

    }


    /**回调验证
     * 实例 
     *   $alipay = new AliPay(
     *       config('system.ali_app_id'),
     *       config('system.ali_private_key'),
     *       config('system.ali_alipay_public_key'),
     *       "https://" . $_SERVER['HTTP_HOST'] . '/api/notify/notify_alipay_order',
     *       "https://" . $_SERVER['HTTP_HOST'] . '/api/index/index'
     *   );
     *   $check = $alipay->back($param);
     */
    public function back($data){
        // 初始化SDK
        $alipayClient = new AopClient($this->alipayConfig);
        if (isset($data['fund_bill_list'])) {
            $data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
        }
        return $alipayClient->rsaCheckV1($data,'','RSA2');
    }
}
















